package com.hue.gulimail.gulimailorder.listener;

import com.hue.common.to.SeckillOrderTo;
import com.hue.gulimail.gulimailorder.entity.OrderEntity;
import com.hue.gulimail.gulimailorder.service.OrderService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Author: 姚凤桥
 * @Date: 2021/12/30 22:34
 * @Description: 监听MQ的order.release.queue队列
 */
@Component
public class OrderListener {
    @Autowired
    private OrderService orderService;

    /**
     * 关闭订单
     *
     * @param order
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitListener(queues = "order.release.queue")
    public void orderReleaseQueueListener(OrderEntity order, Message message, Channel channel) throws IOException {
        try {
            //修改订单状态为已取消(如果订单还没有支付)
            orderService.updateStatusToCancel(order);

            //签收消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            //拒收消息
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }

    /**
     * 创建秒杀订单
     *
     * @param seckillOrder
     * @param message
     * @param channel
     */
    @RabbitListener(queues = "order.seckill.queue")
    public void createSeckillOrder(SeckillOrderTo seckillOrder, Message message, Channel channel) throws IOException {
        try {
            orderService.createSeckillOrder(seckillOrder);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }
}
